import React, { Component } from 'react';
import { Button, Form, Input, Radio, Space, Modal, Select } from "antd";
import { CloseCircleOutlined, PlusOutlined } from '@ant-design/icons';
import TheUpload from "../../../../components/TheUpload";
import { apiActivityLinkList } from "@/request/h5"
import List from './carousellist'
const { Option } = Select
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 3 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};
const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};
class Editor extends Component {
  constructor(props) {
    super(props)
    this.state = {
      fileList: null,
      radioValue: '',
      visible: false,
      configCarouselUri: '',
      newMemberValue: '0',
      activeList: [],
      initialValues: {
        configCarouselType: '',
        newMemberShow: '0',
      },
      arr: [],
      configCarouselSite: "",
    }
  }

  componentDidMount() {
    console.log('sshf');
    this.getActiveList()
    if (this.props.configCarouselSite) {
      this.setState({ configCarouselSite: this.props.configCarouselSite })
    } else {
      this.setState({ configCarouselSite: "" })
    };
    if (this.props.type === 'editor') {
      let value = { ...this.props.data }
      if (value.configCarouselType !== '1') {
        if (value.configCarouselUri !== '') {
          this.setState({
            configCarouselUri: value.configCarouselUri
          })
        }
      } else {
        console.log('aaa');
        let users = []
        let url = []
        if (value.configCarouselUri.indexOf('?') != '-1') {
          url = value.configCarouselUri.split('?')
          console.log(url);
          value.configCarouselUri = url[0]
          users = url[1].split('&')
          let str = ''
          users.map((item) => {
            str = item.split('=')
            this.state.arr.push({
              key: str[0],
              value: str[1]
            })
          })
        } else {
          value.configCarouselUri = value.configCarouselUri.trim()
        }

      }
      // if (parseInt(usePrice) !== -1) {
      //   value.usePrice = 2
      //   this.setState({ usePriceInput: React.$transNum(usePrice, 2, -2), usePrice: 2, useKey: new Date().getTime() })
      // }
      this.formRef.setFieldsValue({ ...value })
      const fileList = [
        {
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: value.configCarouselFilez,
        },
      ]
      this.setState({
        fileList,
        radioValue: value.configCarouselType,
        btnLoading: value.btnLoading,
        dialogCancel: value.dialogCancel,
        configCarouselUri: value.configCarouselUri
        // configCarouselContent: this.props.data.configCarouselContent || ' '
      })
    }
  }

  /**
   * @desc 设置新闻内容表单默认值
   * */
  // setNewsContent = (data) => {
  //     this.setState({
  //         configCarouselContent: data
  //     })
  //     this.formRef.setFieldsValue({ configCarouselContent: data })
  // }
  // 外链地址下拉内容
  async getActiveList() {
    await apiActivityLinkList().then(res => {
      console.log(res);
      if (res.code === 0) {
        this.setState({
          activeList: res.data
        })
      }
    })
  }
  /**
   * @desc 获取图片Id插入到form表单中
   * @param data
   */

  getFileResult = data => {
    console.log(data, 'data');
    if (data.length > 0 && data[0].hasOwnProperty('response') && data[0].response) {
      let str = data[0].response.data
      this.formRef.setFieldsValue({ configCarouselFilez: str })
    } else {
      this.formRef.setFieldsValue({ configCarouselFilez: '' })
    }
  }
  radioChange = (e) => {
    console.log(e, '<Radio onClick={this.radioChange}');
    this.setState({
      configCarouselUri: ''
    }, () => {
      this.formRef.setFieldsValue({ configCarouselUri: '', users: '' })
      const CarouselType = e.target.value
      if (CarouselType !== '1') {
        this.openMadol(CarouselType)
      } else {
        this.setState({
          configCarouselUri: '',
          users: ''
        })
      }
      this.setState({
        radioValue: e.target.value,
      })
    })
  }
  newMemberChange = (e) => {
    this.formRef.setFieldsValue({ newMemberValue: e.target.value })
    this.setState({
      newMemberValue: e.target.value,
    })
  }
  openMadol = (CarouselType) => {
    switch (CarouselType) {
      case '2':
        this.setState({
          visible: true,
          typetitle: '商城门店'
        })
        break;
      case '3':
        this.setState({
          visible: true,
          typetitle: '商城商品'
        })
        break;
      case '4':
        this.setState({
          visible: true,
          typetitle: '线下门店'
        })
        break;
      case '5':
        this.setState({
          visible: true,
          typetitle: '线下商品'
        })
        break;
      case '6':
        this.setState({
          visible: true,
          typetitle: '服务'
        })
        break;
      case '9':
        this.setState({
          visible: true,
          typetitle: '服务类目'
        })
        break;
      case '14':
        this.setState({
          visible: true,
          typetitle: '宠物酒店'
        })
        break;
      case '15':
        this.setState({
          visible: true,
          typetitle: '宠物医院'
        })
        break;
      case '16':
        this.setState({
          visible: true,
          typetitle: '洗护美容'
        })
        break;
      default:
        break;
    }
  }
  onCancel = () => {
    this.setState({
      visible: false
    })
  }
  onOk = (e) => {

    this.setState({
      visible: false
    })
  }
  onFinish = value => {
    if (this.state.radioValue !== '1') {
      value.configCarouselUri = this.state.configCarouselUri
    } else {
      value.configCarouselUri = value.configCarouselUri.trim()
    }
    let str = ''
    if (value.users && value.users.length !== 0) {
      value.users.map((item, index) => {
        str += item.key + '=' + item.value
        if (index + 1 !== value.users.length) {
          str += '&'
        }
        return str
      })
      value.configCarouselUri = value.configCarouselUri.trim() + '?' + str
      delete value.users
    }

    this.props.onFinish(value)
  }
  goDetail(param) {
    let { type, typeId, typeName, storeId, storeName } = param;
    // console.log(param, 'param');
    switch (type) {

      case '2':
        const mallobj = { storeId: typeId, storeName: typeName }
        const mallCarouselUri = JSON.stringify(mallobj);
        // console.log(mallobj, mallCarouselUri)
        this.setState({
          visible: false,
          configCarouselUri: mallCarouselUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })

        break;
      case '3':
        const goodsobj = { goodsId: typeId, goodsName: typeName, storeId: storeId, storeName: storeName }
        const goodsCarouselUri = JSON.stringify(goodsobj);
        this.setState({
          visible: false,
          configCarouselUri: goodsCarouselUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
        })
        break;
      case '4':
        const storeobj = { storeId: typeId, storeName: typeName }
        const storeCarouselUri = JSON.stringify(storeobj);
        this.setState({
          visible: false,
          configCarouselUri: storeCarouselUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '14':
        const hotelobj = { storeId: typeId, storeName: typeName, type: 'HOTEL' }
        const hotelUri = JSON.stringify(hotelobj);
        this.setState({
          visible: false,
          configCarouselUri: hotelUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '15':
        const hospitalobj = { storeId: typeId, storeName: typeName, type: 'HOSPITAL' }
        const hospitalUri = JSON.stringify(hospitalobj);
        this.setState({
          visible: false,
          configCarouselUri: hospitalUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '16':
        const hairdressobj = { storeId: typeId, storeName: typeName, type: "HAIRDRESSING" }
        const hairdressUri = JSON.stringify(hairdressobj);
        this.setState({
          visible: false,
          configCarouselUri: hairdressUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: typeName })
        })
        break;
      case '5':
        const productobj = { productId: typeId, productName: typeName, storeId: storeId, storeName: storeName }
        const productCarouselUri = JSON.stringify(productobj);
        this.setState({
          visible: false,
          configCarouselUri: productCarouselUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
        })
        break;
      case '6':
        const serviceobj = { serviceId: typeId, serviceName: typeName, storeId: storeId, storeName: storeName }
        const serviceCarouselUri = JSON.stringify(serviceobj);
        this.setState({
          visible: false,
          configCarouselUri: serviceCarouselUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: `${typeName},${storeName}` })
        })
        break;
      case '9':
        const categoryobj = { serviceClassifyId: typeId, serviceClassifyName: typeName, }
        const serviceCategorylUri = JSON.stringify(categoryobj);
        this.setState({
          visible: false,
          configCarouselUri: serviceCategorylUri
        }, () => {
          this.formRef.setFieldsValue({ configCarouselUri: `${typeName}` })
        })
        break;
      default:
        break;
    }
  }
  configCarouselUriChange = (e) => {
    this.formRef.setFieldsValue({ users: '' })
    this.setState({ configCarouselUri: e })
  }
  getStringName(carouselUri, type) {
    let str = ''
    if (type !== '1') {
      if (carouselUri !== '') {
        carouselUri = JSON.parse(carouselUri)
        switch (type) {
          case '2':
            str = carouselUri.storeName
            break;
          case '3':
            str = carouselUri.goodsName + carouselUri.storeName
            break;
          case '4': case '14': case '15': case '16':
            str = carouselUri.storeName
            break;
          case '5':
            str = carouselUri.productName + carouselUri.storeName
            break;
          case '6':
            str = carouselUri.serviceName + carouselUri.storeName
            break;
          case '7':
            str = ''
            break;
          case '8':
            str = ''
            break;
          case '9':
            str = carouselUri.serviceClassifyName
            break;
          case '10':
            str = ''
            break;
          case '11':
            str = ''
            break;
          case "12":
            str = ""
            break;
          case "13":
            str = ""
            break;
          default:
            break;
        }
      }
    }
    return str

  }
  render() {
    const { btnLoading, radioValue, visible, typetitle, newMemberValue, configCarouselUri, configCarouselSite, initialValues, activeList, arr } = this.state
    const { dialogCancel } = this.props
    return (
      <Form
        ref={(ref) => {
          this.formRef = ref;
        }}
        {...formItemLayout}
        labelWrap
        onFinish={this.onFinish}
        initialValues={initialValues}
      >
        <Form.Item rules={[{ required: true, message: '请输入标题' }]} name={'configCarouselTitle'} label={'标题'}>
          <Input maxLength={20} />
        </Form.Item>
        <Form.Item
          // extra={`请上传尺寸为1404*1124，大小不超过3M的图片`}
          rules={[{ required: true, message: '请选择图片' }]} name={'configCarouselFilez'} label={'图片'}>

          {this.props.data && this.state.fileList && this.state.fileList.length &&
            <TheUpload isConversion={false} maxSize={10} fileList={this.state.fileList} data={{ attachKey: '1' }} len={1}
              getFileResult={this.getFileResult} />}
          {
            !this.props.data && <TheUpload isConversion={false} maxSize={10} data={{ attachKey: '1' }} len={1}
              getFileResult={this.getFileResult} />
          }
        </Form.Item>
        <Form.Item rules={[{ required: true, message: '请选择' }]} name={'newMemberShow'} label={'是否只对新人展示'} >
          <Radio.Group defaultValue={newMemberValue} >
            <Radio onClick={(e) => this.newMemberChange(e)} value={'1'}>是</Radio>
            <Radio onClick={(e) => this.newMemberChange(e)} value={'0'}>否</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item rules={[{ required: true, message: '请输入位置排序' }, {
          pattern: /^[0-9]*$/,
          message: '只能输入数字'
        }]} name={'configCarouselSort'} label={'位置排序'}>
          <Input maxLength={5} placeholder="*App展示顺序由小到大,相同排序按添加先后顺序展示" />

        </Form.Item>
        {/* <Form.Item rules={[{ required: true, message: '请输入地址链接' }]} name={'configCarouselUri'}
                    label={'地址链接'}>
                    <Input />
                </Form.Item> */}
        <Form.Item rules={[{ required: true, message: '请选择外链' }]} name={'configCarouselType'} label={'外链'}>
          <Radio.Group onChange={this.radioChange} initialValues={radioValue} buttonStyle="solid" optionType='button' >
            <Radio onClick={this.radioChange} value={'1'}>地址链接</Radio>
            {/* <Radio onClick={this.radioChange} value={'2'}>商城门店</Radio> */}
            <Radio onClick={this.radioChange} value={'3'}>商城商品</Radio>
            <Radio onClick={this.radioChange} value={'4'}>线下门店</Radio>
            <Radio onClick={this.radioChange} value={'5'}>线下商品</Radio>
            {/* <Radio onClick={this.radioChange} value={'6'}>服务</Radio> */}
            <Radio onClick={this.radioChange} value={'7'}>邀请有礼</Radio>
            <Radio onClick={this.radioChange} value={'8'}>砍一刀</Radio>
            {/* <Radio onClick={this.radioChange} value={'9'}>服务列表</Radio> */}
            <Radio onClick={this.radioChange} value={'10'}>我的卡包</Radio>
            <Radio onClick={this.radioChange} value={'11'}>宠物出行</Radio>
            {configCarouselSite === "3" || configCarouselSite === "4" ? <Radio onClick={this.radioChange} value={'12'}>正品保障</Radio> : ""}
            <Radio onClick={this.radioChange} value={'13'}>宠物打车</Radio>
            <Radio onClick={this.radioChange} value={'14'}>宠物酒店</Radio>
            <Radio onClick={this.radioChange} value={'15'}>宠物医院</Radio>
            <Radio onClick={this.radioChange} value={'16'}>洗护美容</Radio>
            <Radio onClick={this.radioChange} value={'20'}>领券中心</Radio>
            <Radio onClick={this.radioChange} value={'21'}>全部分类</Radio>
            <Radio onClick={this.radioChange} value={'23'}>商城首页</Radio>
            <Radio onClick={this.radioChange} value={'24'}>拼团频道</Radio>
            <Radio onClick={this.radioChange} value={'26'}>秒杀频道</Radio>
            <Radio onClick={this.radioChange} value={'27'}>签到积分</Radio>
            <Radio onClick={this.radioChange} value={'28'}>上门服务</Radio>
            <Radio onClick={this.radioChange} value={'29'}>上门服务新</Radio>
            <Radio onClick={this.radioChange} value={'30'}>幸运抽奖</Radio>
            <Radio onClick={this.radioChange} value={'31'}>分享官入驻</Radio>
            <Radio onClick={this.radioChange} value={'32'}>宠圈首页</Radio>
            <Radio onClick={this.radioChange} value={'33'}>宠物翻译</Radio>
            <Radio onClick={this.radioChange} value={'34'}>免费问诊</Radio>
            <Radio onClick={this.radioChange} value={'35'}>宠物定位</Radio>
            {/* <Radio onClick={this.radioChange} value={'36'}>官方群列表</Radio> */}
            <Radio onClick={this.radioChange} value={'37'}>宠物鉴别</Radio>
          </Radio.Group>
        </Form.Item>
        {radioValue === '' ? <Form.Item
          // rules={[{ required: true, message: '请输入地址链接' }, {
          //     // pattern: urlReg,
          //     message: '请输入正确的链接地址'
          // }]}
          name={'configCarouselUri'}
          label={'地址链接'}>
          <Input />
        </Form.Item> :
          (["7", "8", "10", "11", "12", "13", "20", "21", "23", "24", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", '36', "37"].includes(radioValue)) ?
            <Form.Item name={'configCarouselUri'}
              label={'选择链接'}>
              <Input readOnly placeholder="无需填写" />
            </Form.Item> :
            <Form.Item name={'configCarouselUri'}
              label={'选择链接'}
              rules={[{ required: radioValue !== '1' ? true : false, message: '请选择链接' }]}
            >
              {radioValue === '1' ? <Select onChange={this.configCarouselUriChange}>
                {
                  activeList.map(item => <Option value={item.activityLink} key={item.id}>{item.activityName}</Option>)
                }

              </Select> : <div style={{ border: '1px solid #ccc', lineHeight: '28px', paddingLeft: '10px', minHeight: '30px' }}>
                {
                  this.getStringName(configCarouselUri, radioValue)
                }

              </div>}
            </Form.Item>


        }
        {
          radioValue === '1' && configCarouselUri !== '' ? <Form.List name="users" initialValue={arr}>
            {(fields, { add, remove }) => (
              <>
                <Form.Item label="参数">
                  <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                    添加参数
                  </Button>
                </Form.Item>
                {fields.map(({ key, name, ...restField }) => (
                  <Form.Item
                    {...formItemLayoutWithOutLabel}
                    required={false}
                    key={key}
                    style={{
                      margin: 0
                    }}
                  >
                    <Space
                      style={{
                        display: 'flex',
                        marginBottom: 0,
                      }}
                      align="baseline"
                    >
                      <Form.Item
                        {...restField}
                        name={[name, 'key']}
                        rules={[
                          {
                            required: true,
                            message: '请输入参数名',
                          },
                        ]}

                      >
                        <Input placeholder="参数名" />
                      </Form.Item>
                      <Form.Item
                        {...restField}
                        name={[name, 'value']}
                        rules={[
                          {
                            required: true,
                            message: '请输入参数值',
                          },
                        ]}
                      >
                        <Input placeholder="参数值" />
                      </Form.Item>
                      <CloseCircleOutlined onClick={() => remove(name)} />
                    </Space>
                  </Form.Item>
                ))}

              </>
            )}
          </Form.List> : ''
        }
        <Modal
          visible={visible}
          onCancel={this.onCancel}

          title={typetitle}
          width='1000px'
          destroyOnClose={true}
          footer={null}
        >
          <List radiotype={radioValue} getList={(e) => this.goDetail(e)} />
        </Modal>
        <div className="p-text-align">
          <Space size="large">
            <Button key="back" onClick={dialogCancel}>
              取 消
            </Button>
            <Button type="primary" loading={btnLoading} htmlType="primary">
              确 定
            </Button>
          </Space>
        </div>
      </Form>
    );
  }
}

export default Editor;
